#
# @author Wójcik Karol <wojcikk@student.agh.edu.pl>
# @licence http://www.gnu.org/copyleft/gpl.html GNU/GPL
#

require 'digest/sha1'

# this model expects a certain database layout and its based on the name/login pattern. 
class User < ActiveRecord::Base

  def self.authenticate(login, pass)
    find_first(["login = ? AND password = ?", login, sha1(pass)])
  end  

  def change_password(pass)
    update_attribute "password", self.class.sha1(pass)
  end
    
  protected

  def self.sha1(pass)
    Digest::SHA1.hexdigest("change-me--#{pass}--")
  end
    
  before_create :crypt_password
  before_update :crypt_password
  
  def crypt_password
    write_attribute("password", self.class.sha1(password))
  end
  
  
  validates_length_of :login, :within => 3..40, :too_long => "Pole 'Login' powinno by&#263; kr&#243;tsze ni&#380; 40 znak&#243;w", :too_short => "Pole 'Login' powinno by&#263; d&#322;u&#380;sze  ni&#380; 3 znaki"
  validates_length_of :password, :within => 5..40, :too_long => "Pole 'Has&#322;o' powinno by&#263; kr&#243;tsze ni&#380; 40 znak&#243;w", :too_short => "Pole 'Has&#322;o' powinno by&#263; d&#322;u&#380;sze  ni&#380; 5 znak&#243;w"
  
  validates_presence_of :name, :message => "Pole 'Imi&#281;' jest puste"
  validates_presence_of :surname, :message => "Pole 'Nazwisko' jest puste"
  validates_presence_of :password,  :message => "Pole 'Has&#322;o' jest puste"
  validates_presence_of :password_confirmation,  :message => "Pole 'Powt&#243;rz has&#322;o' jest puste"
  validates_presence_of :login,  :message => "Pole 'Login' jest puste"
  validates_presence_of :role,  :message => "Pole 'Rola' jest puste"
  validates_presence_of :mark_id,  :message => "Pole 'Stopie&#324;' jest puste"
  validates_presence_of :position_id,  :message => "Pole 'Stanowisko' jest puste"
  
  validates_uniqueness_of :login, :on => :update, :message => "Istnieje ju&#380; taki login, wybierz inny"
  validates_uniqueness_of :login, :on => :create , :message => "Istnieje ju&#380; taki login, wybierz inny"
  
  validates_confirmation_of :password, :on => :create , :on => :update,  :message => "Has&#322;a nie s&#261; takie same"
  
  validates_format_of       :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :message => "Pole 'Adres Email' ma niepoprawny format"

  belongs_to :position
  belongs_to :mark  
  has_many :lessons_users
end
